package app

import (
	"errors"
	"fmt"

	"test/lib/goframe/gf"
	"github.com/douyu/jupiter/pkg/server/xgoframe"
	"github.com/douyu/jupiter/pkg/xlog"

	"test/lib/jupiter/nacos"

	"github.com/douyu/jupiter"
	"github.com/douyu/jupiter/pkg/server"
	"github.com/douyu/jupiter/pkg/util/xgo"
)

type Engine struct {
	jupiter.Application //Jupiter框架引擎

	Group        string       //分组,项目名,读取配置用
	nacosConfig  Config       //配置,连接nacos的配置
	serverConfig ServerConfig //服务配置,从nacos读取

	Error error //错误信息

}

func (a *Engine) Cfg() ServerConfig {
	return a.serverConfig
}

//运行
func (a *Engine) Run(servers ...server.Server) error {
	return a.Application.Run(servers...)
}

//设置错误
func (a *Engine) SetErr(err error) {
	if err != nil && a.Error == nil {
		a.Error = err
	}
}

/*







 */

//捕捉错误
func (a *Engine) stack() {
	if err := recover(); err != nil {
		a = &Engine{}
		a.SetErr(errors.New(fmt.Sprint(err)))
	}
}

func (a *Engine) serveHTTP() error {
	server := xgoframe.StdConfig("http").WithLogger(xlog.DefaultLogger).Build()
	server.Server = gf.New(a.Cfg().Http.Port).Server
	return a.Serve(server)
}

func (a *Engine) getServerConfig(key string) error {

	cfgStr, err := nacos.Get(key)
	if err != nil {
		return err
	}

	cfg, err := DefSetCfg(cfgStr)
	if err != nil {
		return err
	}

	a.serverConfig = cfg
	return nil
}

func newApp(cfg Config, fns ...func() error) *Engine {

	a := &Engine{
		Group:       cfg.Group,
		nacosConfig: cfg,
	}

	//转成nacos的配置,并初始化
	conf, err := cfg.toNacos()
	a.SetErr(err)
	a.SetErr(nacos.New(conf))

	//读取服务配置
	a.SetErr(a.getServerConfig(cfg.Group + ".Config"))

	//这里配置不对会蹦,捕捉
	fns = append(fns, a.serveHTTP)
	a.SetErr(a.Startup(xgo.ParallelWithError(fns...)))

	return a
}
